﻿$(function () {
    
    $('.flexslider').flexslider({
        animation: "slide",
        controlNav: false
    });

    var cateFilData = $('.Category-p-list input#hidFillData').val();
    if (cateFilData != undefined) {
        var cateFil = $('ul.litsCo li a[idata$=' + cateFilData.split('/')[3] + ']');
        $('ul.litsCo li a').removeClass('tabFilActive');
        cateFil.addClass('tabFilActive');
        $(".box-co-left i.arrandCategory").animate({ left: cateFil.attr('ileft') + 'px' });
    }



    //Tab trong danh muc san pham
    $('ul.litsCo li a').click(function () {
        var cmdTab = $(this);
        //di chuyen thanh cuon
        var left = cmdTab.attr('ileft');
        $(".box-co-left i.arrandCategory").animate({ left: left + 'px' });
        //load data
        var cmdFill = $('.Category-p-list input#hidFillData');
        var cate = cmdFill.val().split('/')[0];
        var page = 0;
        var fil = cmdFill.val().split('/')[2];
        var idata = $(this).attr('idata');
        // Filter
        var p_price = '';
        var p_rate = '';
        var p_provider = '';
        var p_color = '';
        var p_size = '';
        var p_attr = '';
        // price
        p_price = $('#hidpriceMin').val() + ';' + $('#hidpriceMax').val();
        // rate

        if ($('#rateValueMin').val() != undefined && $('#rateValueMax').val() != undefined) {
            p_rate = $('#rateValueMin').val() + ';' + $('#rateValueMax').val();
        }

        // provider
        var cmd = $('.ListProviderFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_provider += this.value;
                } else {
                    p_provider += this.value + ',';
                }
            });
        }

        // color
        var cmd = $('.ColorFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_color += this.value;
                } else {
                    p_color += this.value + ',';
                }
            });
        }

        // size
        var cmd = $('.SizeFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_size += this.value;
                } else {
                    p_size += this.value + ',';
                }
            });
        }

        // attr
        var cmd = $('.AttrFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_attr += this.value;
                } else {
                    p_attr += this.value + ',';
                }
            });
        }



        // active tab
        $('ul.litsCo li a').removeClass('tabFilActive');
        cmdTab.addClass('tabFilActive');

        //alert($(this).attr('idata'))
        $('.Category-p-list div.CoListProduct').append('<img id="CategoryLoadingTab" src="/images/icons/gif-load-small.gif" width="30" height="30" alt="loading category tab"/>');
        setTimeout(function () {
            $.ajax({
                type: 'GET',
                dataType: 'html',
                data: { categoryId: cate, page: page + 1, sortdrop: fil, catefil: idata, Price: p_price, Rate: p_rate, Provider: p_provider, Color: p_color, Size: p_size, Attr: p_attr },
                cache: false,
                url: '/Category/CategoryTabSelect',
                success: function (data) {
                    if (data != '') {
                        page = page + 1;
                        $('.Category-p-list div.CoListProduct').html(data);
                        $('.Category-p-list div.CoListProduct').append('<div id="plcPaggingCategoryAjax"></div>');

                        var totalrecord = $('#totalRecord-' + cmdFill.val().split('/')[1]);
                        var RecordByPage = totalrecord.parent().parent().find('.hidRecordByPage').val();
                        var spconlai = (parseInt(totalrecord.text()) - parseInt(RecordByPage));
                        if (spconlai <= 0) {
                            spconlai = 0;
                        }

                        $('.Category-p-list div.CoListProduct').append('<div class="pItem-pagging"><a href="javascript:void(0);" rel="nofollow">Xem thêm (còn <span id="productCountPage">' + spconlai + '</span> sản phẩm)</a></div>');
                        $('.Category-p-list div.CoListProduct #CategoryLoadingTab').remove();
                    } else {
                        $('.Category-p-list div.CoListProduct').html('<div>Không có sản phẩm nào</div>');
                    }
                    paggingMore();
                    //thiet lap lai du lieu hien tai
                    cmdFill.val(cate + '/' + page + '/' + fil + '/' + idata);
                    var url = $(location).attr('href');
                    var urlParam = url.split('?');
                    var urlNew = replaceUrlFilter(url, 'catefil', idata);
                    urlNew = replaceUrlFilter(urlParam[0] + urlNew, 'page', page);
                    window.history.replaceState(null, null, urlNew);

                    //lazy load
                    lzLoading();
                },
                error: function () {
                    Console.log('Đã có lỗi xảy ra!');
                }
            });
        }, 200);

        // di chuyen thanh cuon w: 294/2 = 147px
        //vi tri can di chuyen den = khoang cach left + 1/2 do dai cua box vi tri hien tai
        //neu vi tri chuyen den co toa do nho hon do dai cua (thanh cuon/2) thi left = vi tri can di chuyen
        //neu vi tri chuyen den > do dai thanh cuon thi left = 
        //$("#box").animate({ height: "300px" });

        //var doRongHienTai =cmd.outerWidth();
        //var khoangCachTrai = cmd.offset().left;
        //alert(doRongHienTai);
        //alert(khoangCachTrai);

    });

    // Sap xep cac san pham trong Category
    $('#selectSortCategory').change(function () {
        var cmdFill = $('.Category-p-list input#hidFillData');
        var cate = cmdFill.val().split('/')[0];
        var page = cmdFill.val().split('/')[1];
        var catefil = cmdFill.val().split('/')[3];
        var fil = $(this).val();
        // Filter
        var p_price = '';
        var p_rate = '';
        var p_provider = '';
        var p_color = '';
        var p_size = '';
        var p_attr = '';
        // price
        p_price = $('#hidpriceMin').val() + ';' + $('#hidpriceMax').val();
        // rate
        if ($('#rateValueMin').val() != undefined && $('#rateValueMax').val() != undefined) {
            p_rate = $('#rateValueMin').val() + ';' + $('#rateValueMax').val();
        }

        // provider
        var cmd = $('.ListProviderFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_provider += this.value;
                } else {
                    p_provider += this.value + ',';
                }
            });
        }

        // color
        var cmd = $('.ColorFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_color += this.value;
                } else {
                    p_color += this.value + ',';
                }
            });
        }

        // size
        var cmd = $('.SizeFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_size += this.value;
                } else {
                    p_size += this.value + ',';
                }
            });
        }

        // attr
        var cmd = $('.AttrFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_attr += this.value;
                } else {
                    p_attr += this.value + ',';
                }
            });
        }

        $('.Category-p-list div.CoListProduct').append('<img id="CategoryLoadingTab" src="/images/icons/gif-load-small.gif" width="30" height="30" alt="loading category tab"/>');
        setTimeout(function () {
            $.ajax({
                type: 'GET',
                dataType: 'html',
                data: { categoryId: cate, page: page, sortdrop: fil, catefil: catefil, Price: p_price, Rate: p_rate, Provider: p_provider, Color: p_color, Size: p_size, Attr: p_attr },
                cache: false,
                url: '/Category/CategoryTabSelect',
                success: function (data) {
                    if (data != '') {
                        $('.Category-p-list div.CoListProduct').html(data);
                        $('.Category-p-list div.CoListProduct').append('<div id="plcPaggingCategoryAjax"></div>');
                        var totalrecord = $('#totalRecord-' + cmdFill.val().split('/')[1]);
                        var RecordByPage = totalrecord.parent().parent().find('.hidRecordByPage').val();
                        var spconlai = (parseInt(totalrecord.text()) - parseInt(RecordByPage));
                        if (spconlai <= 0) {
                            spconlai = 0;
                        }
                        $('.Category-p-list div.CoListProduct').append('<div class="pItem-pagging"><a href="javascript:void(0);" rel="nofollow">Xem thêm (còn <span id="productCountPage">' + spconlai + '</span> sản phẩm)</a></div>');
                        $('.Category-p-list div.CoListProduct #CategoryLoadingTab').remove();
                    } else {
                        $('.Category-p-list div.CoListProduct').html('<div>Không có sản phẩm nào</div>');
                    }
                    paggingMore(); //goi su kien phan trang
                    cmdFill.val(cate + '/' + page + '/' + fil + '/' + catefil);
                    var url = $(location).attr('href');
                    var urlNew = replaceUrlFilter(url, 'sortdrop', fil);
                    window.history.replaceState(null, null, urlNew);

                    //lazy load
                    lzLoading();
                },
                error: function () {
                    Console.log('Đã có lỗi xảy ra!');
                }
            });
        }, 200);
    });

    // an hien tab tin trong danh muc
    $('.c-f-t-header').click(function () {
        var cmd = $(this);
        cmd.parent().find('.c-f-t-content').toggle();
    });

    // top 4 promotion by category -Pagging button
    $('.cate-topPromotion a.pIten-back').click(function () {
        var currentPage = $('.cate-topPromotion .hidCurrentPage').val();
        var cate = $('.cate-topPromotion .hidCategory').val();
        var crPage = parseInt(currentPage) - 1;
        if (crPage <= 0) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/PromotionByCatePagging',
            success: function (data) {
                $('.cate-topPromotion .toppromotion-body ul.listp').empty();
                $('.cate-topPromotion .toppromotion-body ul.listp').append(data);
                //set lai cuurentPage
                $('.cate-topPromotion .hidCurrentPage').val(crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });

    });

    $('.cate-topPromotion a.pIten-next ').click(function () {
        var currentPage = $('.cate-topPromotion .hidCurrentPage').val();
        var cate = $('.cate-topPromotion .hidCategory').val();
        var totalpage = $('.cate-topPromotion .hidTotalPage').val();
        var crPage = parseInt(currentPage) + 1;
        if (crPage > totalpage) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/PromotionByCatePagging',
            success: function (data) {
                $('.cate-topPromotion .toppromotion-body ul.listp').empty();
                $('.cate-topPromotion .toppromotion-body ul.listp').append(data);
                //set lai cuurentPage
                $('.cate-topPromotion .hidCurrentPage').val(crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });
    });

    // top 4 PRODUCT NEW by category - Pagging button------------------------------
    $('#placeProductByCateNew a.pIten-back').click(function () {
        var cmd = $('#placeProductByCateNew .hidDataPagging');
        var currentPage = cmd.attr('iCurrentPage');
        var cate = cmd.attr('iCate');
        var crPage = parseInt(currentPage) - 1;
        if (crPage <= 0) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/CategoryProductL1NewPagging',
            success: function (data) {
                $('#placeProductByCateNew ul.listp').empty();
                $('#placeProductByCateNew ul.listp').append(data);
                //set lai cuurentPage
                cmd.attr('iCurrentPage', crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });

    });

    $('#placeProductByCateNew a.pIten-next ').click(function () {
        var cmd = $('#placeProductByCateNew .hidDataPagging');
        var currentPage = cmd.attr('iCurrentPage');
        var cate = cmd.attr('iCate');
        var totalpage = cmd.attr('iTotalPage');
        var crPage = parseInt(currentPage) + 1;
        if (crPage > totalpage) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/CategoryProductL1NewPagging',
            success: function (data) {
                $('#placeProductByCateNew ul.listp').empty();
                $('#placeProductByCateNew ul.listp').append(data);
                //set lai cuurentPage
                cmd.attr('iCurrentPage', crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });
    });

    // top 4 PRODUCT RATEEEEEEEEEEE by category - Pagging button------------------------------
    $('#placeProductRateByCateNew a.pIten-back').click(function () {
        var cmd = $('#placeProductRateByCateNew .hidRatePagging');
        var currentPage = cmd.attr('iCurrentPage');
        var cate = cmd.attr('iCate');
        var crPage = parseInt(currentPage) - 1;
        if (crPage <= 0) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/ProductRateByCatePaging',
            success: function (data) {
                $('#placeProductRateByCateNew ul.listp').empty();
                $('#placeProductRateByCateNew ul.listp').append(data);
                //set lai cuurentPage
                cmd.attr('iCurrentPage', crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });

    });

    $('#placeProductRateByCateNew a.pIten-next ').click(function () {
        var cmd = $('#placeProductRateByCateNew .hidRatePagging');
        var currentPage = cmd.attr('iCurrentPage');
        var cate = cmd.attr('iCate');
        var totalpage = cmd.attr('iTotalPage');
        var crPage = parseInt(currentPage) + 1;
        if (crPage > totalpage) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/ProductRateByCatePaging',
            success: function (data) {
                $('#placeProductRateByCateNew ul.listp').empty();
                $('#placeProductRateByCateNew ul.listp').append(data);
                //set lai cuurentPage
                cmd.attr('iCurrentPage', crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });
    });

    // top 4 PRODUCT BUY MOST by category - Pagging button------------------------------
    $('#placeProductByCateBuyMost a.pIten-back').click(function () {
        var cmd = $('#placeProductByCateBuyMost .hidDataPaggingBuyMost');
        var currentPage = cmd.attr('iCurrentPage');
        var cate = cmd.attr('iCate');
        var crPage = parseInt(currentPage) - 1;
        if (crPage <= 0) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/CategoryProductL1BuyMostPagging',
            success: function (data) {
                $('#placeProductByCateBuyMost ul.listp').empty();
                $('#placeProductByCateBuyMost ul.listp').append(data);
                //set lai cuurentPage
                cmd.attr('iCurrentPage', crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });

    });

    $('#placeProductByCateBuyMost a.pIten-next ').click(function () {
        var cmd = $('#placeProductByCateBuyMost .hidDataPaggingBuyMost');
        var currentPage = cmd.attr('iCurrentPage');
        var cate = cmd.attr('iCate');
        var totalpage = cmd.attr('iTotalPage');
        var crPage = parseInt(currentPage) + 1;
        if (crPage > totalpage) {
            crPage = 1;
        }
        //alert(currentPage);
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { categoryId: cate, page: crPage },
            cache: false,
            url: '/CategoryL1/CategoryProductL1BuyMostPagging',
            success: function (data) {
                $('#placeProductByCateBuyMost ul.listp').empty();
                $('#placeProductByCateBuyMost ul.listp').append(data);
                //set lai cuurentPage
                cmd.attr('iCurrentPage', crPage);
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });
    });
});



/*
        url: duong dan hien tai
        paramNameReplace: ten tham so can thay
        paramNew: gia tri moi tham so can thay
    */
function replaceUrlFilter(url, paramNameReplace, paramValueNew) {
    //tách url gốc thành 2 phần
    var partUrl = url.split('?');
    // tìm tham số cần sưa trên url thứ 2 partUrl[1]
    if (partUrl.length <= 1) {
        return '?' + paramNameReplace + '=' + paramValueNew;
    } else {
        //tách các tham số theo dấu &
        var params = partUrl[1].split('&');
        if (params.length <= 1) {
            //kiểm tra xem tham số này có phải tham số cần thay đổi không ?
            if (params[0].indexOf(paramNameReplace) >= 0) { //có chứa param cần tìm thì thay thế mới ngay
                return '?' + paramNameReplace + '=' + paramValueNew;
            } else {
                return '?' + params[0] + '&' + paramNameReplace + '=' + paramValueNew;
            }
        } else {//nếu có nhiều tham số: duyệt từng thằng tìm và thay thế tham số
            var paramNew = '?';
            for (var i = 0; i < params.length; i++) {
                if (params[i].indexOf(paramNameReplace) < 0) {
                    paramNew += params[i] + '&';
                }
            }
            return paramNew + paramNameReplace + '=' + paramValueNew;
        }
    }
}

// xoa tham so tren url
function removeUrlFilter(url, paramNameRemove) {
    //tách url gốc thành 2 phần
    var partUrl = url.split('?');
    // tìm tham số cần sưa trên url thứ 2 partUrl[1]
    if (partUrl.length <= 1) {
        return partUrl[0];
    } else {
        //tách các tham số theo dấu &
        var params = partUrl[1].split('&');
        if (params.length <= 1) {
            //kiểm tra xem tham số này có phải tham số cần thay đổi không ?
            if (params[0].indexOf(paramNameRemove) >= 0) { //có chứa param cần tìm thì thay thế mới ngay
                return '';
            } else {
                return '?' + params[0];
            }
        } else {//nếu có nhiều tham số: duyệt từng thằng tìm và thay thế tham số
            var paramNew = '?';
            for (var i = 0; i < params.length; i++) {
                if (params[i].indexOf(paramNameRemove) < 0) {
                    paramNew += params[i] + '&';
                } else {
                    paramNew += '';
                }
            }
            return paramNew.substring(0, paramNew.length - 1);
        }
    }
}

//phan trang bang nut them trang trong danh muc san pham
function paggingMore() {
    //phan trang trong danh muc khi load cac tab bang ajax
    $('.pItem-pagging a').click(function () {
        var cmdPagging = $(this);
        var cmdFill = $('.Category-p-list input#hidFillData');
        var cate = cmdFill.val().split('/')[0];
        var currentPage = cmdFill.val().split('/')[1];
        var fil = cmdFill.val().split('/')[2];
        var catefil = cmdFill.val().split('/')[3];
        //var totalPage = $('.hidFillTotalPage').val();
        var _page = parseInt(currentPage) + 1;

        // Filter
        var p_price = '';
        var p_rate = '';
        var p_provider = '';
        var p_color = '';
        var p_size = '';
        var p_attr = '';
        // price
        p_price = $('#hidpriceMin').val() + ';' + $('#hidpriceMax').val();
        // rate
        if ($('#rateValueMin').val() != undefined && $('#rateValueMax').val() != undefined) {
            p_rate = $('#rateValueMin').val() + ';' + $('#rateValueMax').val();
        }

        // provider
        var cmd = $('.ListProviderFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_provider += this.value;
                } else {
                    p_provider += this.value + ',';
                }
            });
        }

        // color
        var cmd = $('.ColorFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_color += this.value;
                } else {
                    p_color += this.value + ',';
                }
            });
        }

        // size
        var cmd = $('.SizeFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_size += this.value;
                } else {
                    p_size += this.value + ',';
                }
            });
        }

        // attr
        var cmd = $('.AttrFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_attr += this.value;
                } else {
                    p_attr += this.value + ',';
                }
            });
        }

        cmdPagging.parent().append('<img class="CategoryLoadingTab" src="/images/icons/gif-load-small.gif" width="30" height="30" alt="loading category tab"/>');
        setTimeout(function () {
            $.ajax({
                type: 'GET',
                dataType: 'html',
                data: { categoryId: cate, page: _page, sortdrop: fil, catefil: catefil, Price: p_price, Rate: p_rate, Provider: p_provider, Color: p_color, Size: p_size, Attr: p_attr },
                cache: false,
                url: '/Category/CategoryTabSelect',
                success: function (data) {

                    if (data != '') {
                        $('.CoListProduct div#plcPaggingCategoryAjax').append('<div class="pItem-pagging-other"><a href="javascript:void(0);" rel="nofollow">Trang ' + _page + '</a></div>');
                        $('.CoListProduct div#plcPaggingCategoryAjax').append(data);
                        $('img.CategoryLoadingTab').remove();
                        if (_page != 1) {

                            var totalrecord = $('#totalRecord-' + (_page - 1));
                            var RecordByPage = totalrecord.parent().parent().find('.hidRecordByPage').val();
                            var totalpage = $('#productCountPage').text();
                            var total = parseInt(totalpage) - parseInt(RecordByPage);
                            if (total <= 0) {
                                total = 0;
                            }
                            $('#productCountPage').text(total);
                            $('.showRecord-' + _page).hide();
                        }

                    } else {
                        _page = _page - 1;
                        cmdPagging.parent().hide();
                        $('img.CategoryLoadingTab').remove();
                    }

                    //thiet lap lai du lieu hien tai
                    cmdFill.val(cate + '/' + _page + '/' + fil + '/' + catefil);
                    var url = $(location).attr('href');
                    var urlNew = replaceUrlFilter(url, 'page', _page);
                    window.history.replaceState(null, null, urlNew);

                    //lazy load
                    lzLoading();
                },
                error: function () {
                    Console.log('Đã có lỗi xảy ra!');
                }
            });
        }, 200);

    });
}
